﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
using Utils;
using Custom;

namespace website.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {

            return View();
        }

        public ActionResult Search(string query,int? page)
        {
			if (!page.HasValue)
				page = 1;
			if (string.IsNullOrEmpty(query))
				return View();
			DateTime start = DateTime.Now;
			List<PostingItem> pl = Config.Engine.Query(query).UniqueTitle();
			ViewData["Count"] = pl.Count;
			ViewData["CurrentPage"] = page;
			List<string> title = new List<string>();
			List<string> description = new List<string>();
			List<string> wikiLink = new List<string>();
			List<double> ranks = new List<double>();
			Dictionary<string, string> tokens = new Dictionary<string, string>();
			foreach (string s in query.Split(new char[] {'\"', ' ', '|'},StringSplitOptions.RemoveEmptyEntries))
				tokens[s] = Config.Engine.Tokenize(s);
			foreach (KeyValuePair<string, string> kv in tokens)
				query = query.Replace(kv.Key, kv.Value);
			for (int i = Math.Max((page.Value - 1) * Config.PerPage,0);i<pl.Count &&  i < page * Config.PerPage; ++i)
			{
				string fullItem = Utilities.FullDescription(pl[i].TitleNumber);
				Config.Engine.InitStream(fullItem);
				string currentTitle = Config.Engine.GetTitle().Trim();
				wikiLink.Add(currentTitle.Replace(' ','_'));
				ranks.Add(Config.Engine.GetScore(pl[i].TitleNumber));
				int tokenPos = 0;
				StringBuilder titleBuilder = new StringBuilder(50);
				StringBuilder textBuilder = new StringBuilder(200);
				while (tokenPos < pl[i].WordPosition)
				{
					TokenItem item = Config.Engine.GetToken();
					if (item.Type == TokenType.Bad)
						break;
					if (string.IsNullOrEmpty(item.Token))
						--tokenPos;
					item.Word = ' ' + item.Word.Trim();
					if (tokens.Values.Contains(item.Token))
						item.Word = "<span class=\"match"+Enum.GetName(typeof(TokenType),item.Type)+"\">" + item.Word + "</span>";
					if (item.Type == TokenType.Title)
						titleBuilder.Append(item.Word);
					++tokenPos;
				}
				int visableLen = 0;
				while (visableLen < 250)
				{
					TokenItem item = Config.Engine.GetToken();
					if (item.Type == TokenType.Bad)
						break;
					item.Word = ' ' + item.Word.Trim();
					visableLen += item.Word.Length;
					if (tokens.Values.Contains(item.Token))
						item.Word = "<span class=\"match" + Enum.GetName(typeof(TokenType), item.Type) + "\">" + item.Word + "</span>";
					if (item.Type == TokenType.Title)
						titleBuilder.Append(item.Word);
					else
						textBuilder.Append(item.Word);
				}
				title.Add(titleBuilder.ToString());
				description.Add(textBuilder.ToString());
			}
			ViewData["Links"] = wikiLink;
			ViewData["Titles"] = title;
			ViewData["Description"] = description;
			ViewData["Query"] = query;
			ViewData["PageRank"] = ranks;
			string timedif = (DateTime.Now - start).TotalSeconds.ToString("0.0000");
			ViewData["Time"] = timedif;
			Logger.append(string.Format("zapytanie: {0} ; czas: {1}\n", query, timedif), Logger.INFO);
            return View();
        }
    }
}